package net.wsfcp.android.ui.view.main.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.FutureTarget;
import com.bumptech.glide.request.target.Target;

import net.wsfcp.android.R;
import net.wsfcp.android.base.BaseActivity;
import net.wsfcp.android.bean.resultbean.TabBean;
import net.wsfcp.android.event.ReloadOrderEvent;
import net.wsfcp.android.event.ReloadPageEvent;
import net.wsfcp.android.http.mvp.contract.MainContract;
import net.wsfcp.android.event.OpenMenuEvent;
import net.wsfcp.android.http.UrlHelper;
import net.wsfcp.android.http.mvp.presenter.MainPresenter;
import net.wsfcp.android.ui.view.main.fragment.MainFragment;
import net.wsfcp.android.ui.view.my.fragment.MyFragment;
import net.wsfcp.android.utils.CommonUtils;
import net.wsfcp.android.utils.SpUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.ExecutionException;

import butterknife.BindView;

//主页
public class MainActivity extends BaseActivity<MainPresenter> implements MainContract.MainView {
    @BindView(R.id.mPager)
    ViewPager mPager;
    @BindView(R.id.rd_button)
    RadioGroup mGroup;
    @BindView(R.id.draw)
    DrawerLayout drawerLayout;

    private ArrayList<Fragment> fragmentList = new ArrayList<>();
    private ArrayList<TabBean> tabList = new ArrayList<>();
    MainFragment mainFragment;
    MyFragment myFragment;
    myFragmentPagerAdapter adapter;

    private long mExitTime;
    private String phoneNumber = "";

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            ((RadioButton) mGroup.getChildAt(msg.what)).setCompoundDrawables(null, hashMap.get(msg.what), null, null);

        }
    };

    //<下标，图片>
    HashMap<Integer, Drawable> hashMap = new HashMap();
    //<viewId，下标>
    HashMap<Integer, Integer> hashMapIds = new HashMap();

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }


    @Override
    public void onBackPressed() {

        if (drawerLayout.isDrawerOpen(Gravity.LEFT)) {
            drawerLayout.closeDrawer(Gravity.LEFT);

        } else if (fragmentList.get(mPager.getCurrentItem()) instanceof MainFragment && ((MainFragment) fragmentList.get(mPager.getCurrentItem())).getWeb().canGoBack()) {
            ((MainFragment) fragmentList.get(mPager.getCurrentItem())).getWeb().goBack();

        } else {

            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                toast("再次点击退出程序");
                mExitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
        }
    }


    //接收订阅的事件
    @Subscribe(threadMode = ThreadMode.POSTING)
    public void openMenu(OpenMenuEvent openMenuEvent) {
        if (drawerLayout.isDrawerOpen(Gravity.LEFT)) {
            drawerLayout.closeDrawer(Gravity.LEFT);


        } else {
            drawerLayout.openDrawer(Gravity.LEFT);

        }

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

    }


    @Override
    protected MainPresenter loadPresenter() {
        return new MainPresenter();
    }

    @Override
    protected void initData() {
        mPresenter.getTab();
    }

    @Override
    protected void initListener() {
        mGroup.setOnCheckedChangeListener(new MyCheckChangeListener());
        mPager.addOnPageChangeListener(new MyOnPageChangeListener());
        drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(@NonNull View view, float v) {
            }

            @Override
            public void onDrawerOpened(@NonNull View view) {
                EventBus.getDefault().post(new ReloadPageEvent());
            }

            @Override
            public void onDrawerClosed(@NonNull View view) {
            }

            @Override
            public void onDrawerStateChanged(int i) {

            }
        });

    }


    @Override
    protected void initView() {

        ArrayList<TabBean> tabBeans = SpUtils.getInstance().getTab();
        if (tabBeans != null) {
            tabList.clear();
            tabList.addAll(tabBeans);
            initTabs();
            initFragments();
        } else {
            initBaseTabs();
            initBaseFragments();
        }


    }


    private void initTabs() {

        if (tabList != null && tabList.size() > 0) {
            mGroup.removeAllViews();
            for (int i = 0; i < tabList.size(); i++) {
                final TabBean tabBean = tabList.get(i);
                final RadioButton tempButton = new RadioButton(this);

                tempButton.setButtonDrawable(null);//去掉默认选中框


                //动态添加图
                getImage(tabBean.getSelectIconUri(), tabBean.getUnselectIconUri(), i);

                //动态添加文字颜色
                tempButton.setText(tabBean.getName());
                tempButton.setTextColor(CommonUtils.colorSelector(tabBean.getSelectFontColor().isEmpty() ? getResources().getColor(R.color.tab_on) : CommonUtils.getColor(tabBean.getSelectFontColor()), getResources().getColor(R.color.tab_off)));
                Log.e("颜色", CommonUtils.getColor(tabBean.getSelectFontColor()) + "");
                tempButton.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
                tempButton.setPadding(dp(5), dp(5), dp(5), dp(5));// 设置文字距离按钮四周的距离
                tempButton.setGravity(Gravity.CENTER);     //此处相当于布局文件中的Android：gravity属性
//动态添加id

                int randomId = View.generateViewId();
                Log.e("随机id", randomId + "");
                switch (tabBean.getMenuType()) {
                    case 0://网页
                        hashMapIds.put(randomId, i);
                        tempButton.setId(randomId);
                        break;
                    case 1://首页
                        hashMapIds.put(R.id.rb_main, i);
                        tempButton.setId(R.id.rb_main);
                        tempButton.setChecked(true);
                        break;
                    case 2://电话
                        phoneNumber = tabBean.getContactNumber();
                        hashMapIds.put(R.id.rb_phone, i);
                        tempButton.setId(R.id.rb_phone);
                        tempButton.setOnClickListener(this);
                        break;
                    case 3://留言
                        hashMapIds.put(randomId, i);
                        tempButton.setId(randomId);
                        break;
                    case 4://会员
                        hashMapIds.put(R.id.rb_mine, i);
                        tempButton.setId(R.id.rb_mine);
                        break;
                    case 5://购物车
                        hashMapIds.put(randomId, i);
                        tempButton.setId(randomId);
                        break;
                    case 6://栏目
                        hashMapIds.put(randomId, i);
                        tempButton.setId(randomId);
                        break;

                    default:
                        hashMapIds.put(randomId, i);
                        tempButton.setId(randomId);
                        break;


                }


                RadioGroup.LayoutParams lpBtn = new RadioGroup.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f);//此处我需要均分高度就在heignt处设0,1.0f即设置权重是1，页面还有其他一个控件,1：1高度就均分了
                //此处相当于布局文件中的Android:layout_gravity属性
                lpBtn.gravity = Gravity.CENTER;

                mGroup.addView(tempButton, lpBtn);
            }
        }
    }


    //初始化页面
    private void initFragments() {
//        0=自定义菜单 1=首页 2=电话 3=留言 4=会员 5=购物车 6=栏目
//        fragmentList.clear();
        for (int i = 0; i < tabList.size(); i++) {

            switch (tabList.get(i).getMenuType()) {
                case 0:
                    MainFragment webFragment = new MainFragment();
                    webFragment.setUrl(tabList.get(i).getPageLink());
                    fragmentList.add(webFragment);

                    break;
                case 1:
                    mainFragment = new MainFragment();
                    mainFragment.setUrl(UrlHelper.getUserMainUrl());
                    fragmentList.add(mainFragment);
                    break;
                case 2://电话

                    break;
                case 3://留言
                    MainFragment messageFragment = new MainFragment();
                    messageFragment.setUrl(tabList.get(i).getPageLink());
                    fragmentList.add(messageFragment);
                    break;
                case 4://会员
                    myFragment = new MyFragment();
                    fragmentList.add(myFragment);
                    break;
                case 5://购物车
                    MainFragment m = new MainFragment();
                    m.setUrl(tabList.get(i).getPageLink());
                    fragmentList.add(m);
                    break;
                case 6://栏目
                    MainFragment lanmuFragment = new MainFragment();
                    lanmuFragment.setUrl(tabList.get(i).getPageLink());
                    fragmentList.add(lanmuFragment);
                    break;
                default:
                    MainFragment defaultFragment = new MainFragment();
                    defaultFragment.setUrl(tabList.get(i).getPageLink());
                    fragmentList.add(defaultFragment);
                    break;

            }


        }

        //ViewPager设置适配器
        adapter = new myFragmentPagerAdapter(getSupportFragmentManager(), fragmentList);
        mPager.setAdapter(adapter);

        mPager.setOffscreenPageLimit(fragmentList.size() - 1);
        //ViewPager显示第一个Fragment
        mPager.setCurrentItem(0);
        //ViewPager页面切换监听
    }


    private void initBaseTabs() {
        for (int i = 0; i < 3; i++) {
            TabBean tabBean = new TabBean();

            switch (i) {
                case 0:
                    tabBean.setName("首页");
                    tabBean.setUnselectIconUriDef(R.mipmap.index_icon_14);
                    tabBean.setSelectIconUriDef(R.mipmap.index_icon_15);

                    break;
                case 1:
                    tabBean.setName("电话");
                    tabBean.setUnselectIconUriDef(R.mipmap.index_icon_16);
                    tabBean.setSelectIconUriDef(R.mipmap.index_icon_17);
                    tabBean.setMenuType(2);
                    break;
                case 2:
                    tabBean.setName("我的");
                    tabBean.setUnselectIconUriDef(R.mipmap.index_icon_20);
                    tabBean.setSelectIconUriDef(R.mipmap.index_icon_21);
                    break;


            }


            tabList.add(tabBean);
        }


        if (tabList != null && tabList.size() > 0) {
            mGroup.removeAllViews();
            for (int i = 0; i < tabList.size(); i++) {
                TabBean tabBean = tabList.get(i);
                RadioButton tempButton = new RadioButton(this);

                tempButton.setButtonDrawable(null);//去掉默认选中框
                //动态添加图片
                Drawable drawable = CommonUtils.drawableSelector(getResources().getDrawable(tabBean.getSelectIconUriDef()), getResources().getDrawable(tabBean.getUnselectIconUriDef()));
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                tempButton.setCompoundDrawables(null, drawable, null, null);
                //动态添加文字颜色
                tempButton.setText(tabBean.getName());
                tempButton.setTextColor(CommonUtils.colorSelector(getResources().getColor(R.color.tab_on), getResources().getColor(R.color.tab_off)));
                tempButton.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
                tempButton.setPadding(dp(5), dp(5), dp(5), dp(5));// 设置文字距离按钮四周的距离
                tempButton.setGravity(Gravity.CENTER);     //此处相当于布局文件中的Android：gravity属性
//动态添加id
                switch (i) {
                    case 0:
                        tempButton.setId(R.id.rb_main);
                        tempButton.setChecked(true);
                        break;
                    case 1:
                        tempButton.setId(R.id.rb_phone);
                        tempButton.setOnClickListener(this);
                        break;
                    case 2:
                        tempButton.setId(R.id.rb_mine);
                        break;
                }

                RadioGroup.LayoutParams lpBtn = new RadioGroup.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f);//此处我需要均分高度就在heignt处设0,1.0f即设置权重是1，页面还有其他一个控件,1：1高度就均分了
                //此处相当于布局文件中的Android:layout_gravity属性
                lpBtn.gravity = Gravity.CENTER;

                mGroup.addView(tempButton, lpBtn);
            }
        }
    }


    //初始化页面
    private void initBaseFragments() {
        mainFragment = new MainFragment();
        mainFragment.setUrl(UrlHelper.getUserMainUrl());
        myFragment = new MyFragment();

        fragmentList.clear();
        fragmentList.add(mainFragment);
        fragmentList.add(myFragment);
        //ViewPager设置适配器
        adapter = new myFragmentPagerAdapter(getSupportFragmentManager(), fragmentList);
        mPager.setAdapter(adapter);
        //ViewPager显示第一个Fragment
        mPager.setCurrentItem(0);
        //ViewPager页面切换监听
    }


    @Override
    protected void otherViewClick(View view) {

        switch (view.getId()) {
            case R.id.rb_phone:

                new AlertDialog.Builder(this).setTitle("拨打电话")
                        .setMessage(UrlHelper.PHONE_NUM).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                        dialogInterface.dismiss();
                        Intent intent = new Intent(Intent.ACTION_DIAL);
                        Uri data = Uri.parse("tel:" + (phoneNumber.isEmpty() ? UrlHelper.PHONE_NUM : phoneNumber));
                        intent.setData(data);
                        startActivity(intent);

                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                        dialogInterface.dismiss();
                    }
                }).create().show();

                break;

        }

    }

    @Override
    public void getTabSuccess(ArrayList<TabBean> bean) {
        SpUtils.getInstance().saveTab(bean);

        for (int i = 0; i < bean.size(); i++) {
            TabBean tabBean = bean.get(i);

            download(tabBean.getSelectIconUri());
            download(bean.get(i).getUnselectIconUri());
        }


    }

    @Override
    public void getTabFail(String failMsg) {
        toast(failMsg);
    }


    /**
     * RadioButton切换Fragment
     */
    private class MyCheckChangeListener implements RadioGroup.OnCheckedChangeListener {


        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            switch (checkedId) {
                case R.id.rb_main:
                    //ViewPager显示第一个Fragment且关闭页面切换动画效果
                    mPager.setCurrentItem(0, false);
                    break;
                case R.id.rb_phone:
//                    mPager.setCurrentItem(1, false);


                    break;
                case R.id.rb_mine:
                    if (adapter != null) {
                        mPager.setCurrentItem(adapter.getCount() - 1, false);
                    }
                    break;

                default:
                    if (adapter != null) {
                        if (tabList.size() == fragmentList.size()) {
                            mPager.setCurrentItem(hashMapIds.get(checkedId), false);
                        } else {

                            if (hashMapIds.get(R.id.rb_phone) > hashMapIds.get(checkedId)) {
                                mPager.setCurrentItem(hashMapIds.get(checkedId), false);
                            } else {
                                mPager.setCurrentItem(hashMapIds.get(checkedId) - 1, false);
                            }
                        }


                    }
                    break;

            }
        }
    }

    /**
     * ViewPager切换Fragment,RadioGroup做相应变化
     */
    private class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {


            switch (position) {
                case 0:
                    drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
                    break;
                default:
                    drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
                    break;


            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    }


    public class myFragmentPagerAdapter extends FragmentPagerAdapter {
        ArrayList<Fragment> list;

        public myFragmentPagerAdapter(FragmentManager fm, ArrayList<Fragment> list) {
            super(fm);
            this.list = list;
        }

        @Override
        public Fragment getItem(int position) {
            return list.get(position);
        }

        @Override
        public int getCount() {
            return list.size();
        }
    }


    public void getImage(final String SelectIconUri, final String UnselectIconUri, final int finalI) {

        new Thread() {
            @Override
            public void run() {
                //需要在子线程中处理的逻辑
                try {
                    Drawable select = Glide.with(MainActivity.this)
                            .load(SelectIconUri)
                            .into(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                            .get();

                    Drawable unselect = Glide.with(MainActivity.this)
                            .load(UnselectIconUri)
                            .into(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                            .get();
                    Drawable drawable = CommonUtils.drawableSelector(select, unselect);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    Message msg = new Message();
                    hashMap.put(finalI, drawable);
                    msg.what = finalI;
                    handler.sendMessage(msg);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }
        }.start();

    }

    public void download(final String url) {

        new AsyncTask<Void, Integer, File>() {

            @Override
            protected File doInBackground(Void... params) {
                File file = null;
                try {
                    FutureTarget<File> future = Glide
                            .with(MainActivity.this)
                            .load(url)
                            .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL);

                    file = future.get();

//                    // 最后通知图库更新
//                    sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
//                            Uri.fromFile(new File(destFile.getPath()))));


                } catch (Exception e) {
//                    Log.e(TAG, e.getMessage());
                }
                return file;
            }

            @Override
            protected void onPostExecute(File file) {

//                Toast.makeText(ImageActivity.this, "saved in Pictures/GankBeauty", Toast.LENGTH_SHORT).show();
            }

            @Override
            protected void onProgressUpdate(Integer... values) {
                super.onProgressUpdate(values);
            }
        }.execute();
    }

}
